package com.example.keli.ui.common;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.keli.R;
import com.example.keli.base.App;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.utils.DensityUtil;
import com.example.keli.base.utils.FileUtils;
import com.example.keli.base.widget.glide.GlideCornerTransform;
import com.example.keli.base.utils.GlideUtil;
import com.flyco.roundview.RoundTextView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

public class ShareActivity extends BaseActivity {

    @BindView(R.id.ll_image)
    LinearLayout llImage;
    @BindView(R.id.iv_cancel)
    ImageView ivCancel;
    @BindView(R.id.iv_cover)
    ImageView ivCover;
    @BindView(R.id.iv_qr)
    ImageView ivQr;
    @BindView(R.id.iv_wechat)
    ImageView ivWechat;
    @BindView(R.id.iv_wechat_circle)
    ImageView ivWechatCircle;
    @BindView(R.id.iv_download)
    ImageView ivDownload;
    @BindView(R.id.tv_cancel)
    RoundTextView tvCancel;

    private UMWeb umWeb;

    public static void start(Context context, String uid, String aaid, String nickname, String imgUrl) {
        Intent intent = new Intent(context, ShareActivity.class);
        intent.putExtra("uid", uid);
        intent.putExtra("aaid", aaid);
        intent.putExtra("nickname", nickname);
        intent.putExtra("imgUrl", imgUrl);
        context.startActivity(intent);
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_share;
    }

    @Override
    protected void bindData() {
        llImage.setDrawingCacheEnabled(true);
        llImage.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        llImage.setDrawingCacheBackgroundColor(Color.WHITE);

        String uid = getIntent().getStringExtra("uid");
        String aaid = getIntent().getStringExtra("aaid");
        String nickname = getIntent().getStringExtra("nickname");
        String imgUrl = getIntent().getStringExtra("imgUrl");
        //二维码信息
        String qRcontent = "http://keli.h5ck.com/register?by_convey_code=" + App.getAccount().getConvey_code();
        String shareUrl = "http://keli.h5ck.com/girl/"+ uid +"?aaid="+ aaid +"&by_convey_code="+ App.getAccount().getConvey_code();
        UMImage image = new UMImage(ShareActivity.this, imgUrl);
        umWeb = new UMWeb(shareUrl);
        umWeb.setTitle("可哩App最好的短视频才艺比拼平台");//标题
        umWeb.setThumb(image);  //缩略图
        umWeb.setDescription(nickname +"在可哩参与比赛，快来给TA助力投票吧");//描述

        GlideCornerTransform transformation = new GlideCornerTransform(this, DensityUtil.dip2px(this, 5));
        transformation.setExceptCorner(false, false, true, true);
        GlideUtil.displayTransform(ShareActivity.this, ivCover, imgUrl, transformation);
        createQRCode(qRcontent);
    }

    @OnClick({R.id.iv_cancel, R.id.iv_wechat, R.id.iv_wechat_circle, R.id.iv_download, R.id.tv_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_cancel:
                finish();
                break;
            case R.id.iv_wechat:
                shareToChat();
                break;
            case R.id.iv_wechat_circle:
                shareToChatCircle();
                break;
            case R.id.iv_download:
                download();
                break;
            case R.id.tv_cancel:
                finish();
                break;
        }
    }

    private void download() {
        requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, "下载图片需要写入权限", new GrantedResult() {
            @Override
            public void onResult(boolean granted) {
                if (granted){
                    Bitmap bitmap = llImage.getDrawingCache();
                    final boolean result = FileUtils.saveImageToGallery(ShareActivity.this, bitmap);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (result){
                                toast("图片下载成功");
                            }else {
                                toast("图片下载失败");
                            }
                        }
                    }, 1000L);
                }else {
                    toast("下载图片需要写入权限");
                }
            }
        });


    }

    private void createQRCode(final String qrContent) {
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                Bitmap qr = QRCodeEncoder.syncEncodeQRCode(qrContent, BGAQRCodeUtil.dp2px(ShareActivity.this, 80), Color.BLACK);
                return qr;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null) {
                    ivQr.setImageBitmap(bitmap);
                } else {
                    //默认的二维码
                }
            }
        }.execute();
    }

    private void shareToChat() {
        ShareAction action = new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener);
        action.withMedia(umWeb);
        action.share();
    }

    private void shareToChatCircle() {
        ShareAction action = new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener);
        action.withMedia(umWeb);
        action.share();
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            //由于微信调整接口，由于‘强制分享至不同群’等滥用分享能力，原先的cancel和success事件将统一为success
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            toast("分享失败啦"+t.getMessage());
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            toast("分享已取消");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
